package com.sanji.sjmallmodule.goods;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sanji.sjmallapp.BaseActivity;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigAPI;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmanager.http.NoHttpCallBack;
import com.sanji.sjmallmanager.http.NoHttpListener;
import com.sanji.sjmallmodule.main.BannerBean;
import com.sanji.sjmallmodule.main.MainActivity;
import com.sanji.sjmallmodule.main.ViewPagerAdapter;
import com.sanji.sjmallutils.ImageSizeUtil;
import com.sanji.sjmallutils.Tools;
import com.sanji.sjmallwidget.BannerPagerView;
import com.sanji.sjmallwidget.BannerPointView;
import com.sanji.sjmallwidget.MyListView;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.sanji.sjmallconfig.ConfigAPI.ADD_SHOPCAR;

/****
 * 商品详情
 *****/
public class GoodsDetailsActivity extends BaseActivity implements View.OnClickListener, GoodsModelAdapter.buyGoodsNumberListener, NoHttpListener {
    @BindView(R.id.common_left_tv)
    TextView commonLeftTv;
    @BindView(R.id.common_right_img)
    ImageView commonRightImg;
    @BindView(R.id.common_back_img)
    ImageView commonBackImg;
    @BindView(R.id.goods_details_viewpager)
    BannerPagerView goodsViewpager;
    @BindView(R.id.goods_free_gifts_linear)
    LinearLayout freeGiftsLinear;
    @BindView(R.id.goods_params)
    TextView goodsParamsTv;
    @BindView(R.id.goods_graphic_details_tv)
    TextView goodsGraphicDetailsTv;
    @BindView(R.id.goods_buy_now_btn)
    Button buyNowBtn;
    View goodsView;
    @BindView(R.id.goods_details_point_view)
    BannerPointView mPointView;
    @BindView(R.id.goods_name)
    TextView goodsName;
    @BindView(R.id.goods_deal_bumber)
    TextView goodsDealNumber;
    @BindView(R.id.goods_deal_credit_number)
    TextView goodsCreditNumber;
    @BindView(R.id.goods_details_price)
    TextView goodsPrice;
    @BindView(R.id.goods_params_view)
    View goodsParamsView;
    @BindView(R.id.activity_goods_details)
    RelativeLayout activityGoodsDetails;
    private int[] imageResIDs;
    private List<ImageView> imageList;
    private ViewPagerAdapter pagerAdapter;
    //动态添加赠品布局
    private List<GoodsBean> freeGiftsList;
    //popupWindow弹出
    private PopupWindow popupWindow;
    private PopupWindow shopCarWindow;//加入购物车window
    private TextView pop_goods_name;//商品名字
    private TextView pop_purchase_number;//采购的数量
    private TextView pop_goods_money;//商品总额
    private TextView pop_add_shopcar;//加入购物车
    private MyListView pop_list_view;//listView
    private ImageView pop_delete;
    private GoodsModelAdapter popAdapter;
    private List<GoodsBean> popGoodsData;//存放sku
    private int buyTotalNumber;//购买的总数量
    private double buyAccount;//购买的总价格
    private String goodsCode;//商品
    private Request<JSONObject> request;
    private String goodsDetailUrl = "";
    List<BannerBean> bannerList;
    private String goodsNameStr;//商品名称
    private Set<GoodsBean> shopCarSet;//加入购物车
    private GoodsParamBean goodsParamBean;//产品参数
    private String graphicDetails = "";//图文详情
    private String goodsType;//商品类型

    private TextView continueTv;//继续选购
    private TextView setAccountTv;//马上结算
    private Handler mHandler = new Handler();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods);
        ButterKnife.bind(this);
        initView();
        //网络请求商品详情数据
        requestData();
    }

    public void initView() {
        commonLeftTv.setText(getString(R.string.goods_details));
        commonRightImg.setVisibility(View.VISIBLE);
        commonRightImg.setImageResource(R.mipmap.fragment_shopcar_select);
        commonBackImg.setOnClickListener(this);
        goodsView = findViewById(R.id.goods_view);
        imageList = new ArrayList<>();
        freeGiftsList = new ArrayList<>();
        popGoodsData = new ArrayList<>();
        shopCarSet = new HashSet<>();
        bannerList = new ArrayList<>();
        //
        goodsParamsTv.setOnClickListener(this);
        goodsGraphicDetailsTv.setOnClickListener(this);
        buyNowBtn.setOnClickListener(this);
        //初始化数据
        popAdapter = new GoodsModelAdapter(popGoodsData, this);
        popAdapter.setOnBuyGoodsNumberListener(this);
        commonRightImg.setOnClickListener(this);
        goodsCode = getIntent().getStringExtra("goodsCode");
        goodsType = getIntent().getStringExtra("goodsType");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back_img:
                finish();
                break;
            case R.id.goods_params:
                //产品参数
                intent = new Intent(this, GoodsParamsActivity.class);
                intent.putExtra("goodsParam", goodsParamBean);
                startActivity(intent);
                break;
            case R.id.goods_graphic_details_tv:
                intent = new Intent(this, GoodsGraphicActivity.class);
                if (graphicDetails.equals("")) {
                    Tools.toastTools(mCtx, getString(R.string.goods_no_grapic));
                } else {
                    intent.putExtra("graphicDetails", graphicDetails);
                    startActivity(intent);
                }
                break;
            case R.id.goods_buy_now_btn:
                showPopWindow();
                break;
            case R.id.pop_add_shopcar:
                requestAddShopCar();
                break;
            case R.id.common_right_img:
                Intent mIntent = new Intent(ConfigConts.ACTION_FRAGMENT_PAGER);
                mIntent.putExtra("index", 2);
                sendBroadcast(mIntent);

                intent = new Intent(this, MainActivity.class);
                intent.putExtra("from_detail", true);
                startActivity(intent);
//                finishActivity();
                break;
        }
    }

    /**
     * 网络请求当前数据
     */
    public void requestData() {
        String userId = myShare.getString(ConfigConts.USER_ID, null);
        goodsDetailUrl = ConfigAPI.GOODS_DETAILS_URL + goodsCode + "/" + goodsType + "?userId=" + userId;
        request = NoHttp.createJsonObjectRequest(goodsDetailUrl, RequestMethod.GET);
        request.setCancelSign(goodsDetailUrl.hashCode());
        NoHttpCallBack.getInstance().add(mCtx, goodsDetailUrl.hashCode(), request, this, true, true);
    }

    /**
     * popwindow弹出，选择商品数量
     */
    public void showPopWindow() {
        final WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.alpha = 0.8f;
        this.getWindow().setAttributes(lp);
        if (null == popupWindow) {
            View view = LayoutInflater.from(this).inflate(R.layout.activity_goods_detail_pop, null);
            pop_goods_name = (TextView) view.findViewById(R.id.pop_goods_name);
            pop_delete = (ImageView) view.findViewById(R.id.pop_delete_img);
            pop_add_shopcar = (TextView) view.findViewById(R.id.pop_add_shopcar);
            pop_goods_money = (TextView) view.findViewById(R.id.pop_goods_money);
            pop_purchase_number = (TextView) view.findViewById(R.id.pop_goods_purchase_number);
            pop_list_view = (MyListView) view.findViewById(R.id.pop_list_view);
            //
            popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            popupWindow.setBackgroundDrawable(this.getResources().getDrawable(R.color.colorWhite));
            popupWindow.setFocusable(true);
            popupWindow.setOutsideTouchable(true);
            popupWindow.setAnimationStyle(R.style.my_popwindow);
            //增加数据
            pop_goods_name.setText(goodsNameStr);
            pop_list_view.setAdapter(popAdapter);
            popAdapter.notifyAdapter(popGoodsData);
        }
        //设置popview在y上的偏移量
        int y = ImageSizeUtil.setImageWidth(this, 1);
        popupWindow.showAsDropDown(commonLeftTv, 0, y / 2);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                lp.alpha = 1.0f;
                GoodsDetailsActivity.this.getWindow().setAttributes(lp);
            }
        });
        pop_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        pop_add_shopcar.setOnClickListener(this);

    }

    /**
     * 选择的商品信息
     */
    @Override
    public void buyGoodsNumber() {
        getBuyNumberAndAcount();
    }

    /**
     * 计算商品购买数量和购买总价格
     */
    public void getBuyNumberAndAcount() {
        buyTotalNumber = 0;
        buyAccount = 0;
        for (GoodsBean bean : popGoodsData) {
            buyTotalNumber += bean.getBuyNumber();
            buyAccount = Tools.add(buyAccount, Tools.multiply(bean.getPhonePrice(), bean.getBuyNumber()));
            if (bean.getBuyNumber() > 0) {
                shopCarSet.add(bean);
            } else {
                shopCarSet.remove(bean);
            }
        }
        pop_purchase_number.setText(buyTotalNumber + "");
        pop_goods_money.setText("￥" + buyAccount);
    }

    @Override
    public void onSuccessed(int what, Response response) {
        if (what == goodsDetailUrl.hashCode()) {
            JSONObject json = (JSONObject) response.get();
            String status = json.optString(ConfigConts.STATUS_STRING);
            goodsParamBean = new GoodsParamBean();
            BannerBean bean = null;
            if (status.equals(ConfigConts.STATUS_SUCCESS)) {
                freeGiftsList.clear();
                try {
                    JSONObject result = json.optJSONObject("result");
                    if (null != result) {
                        activityGoodsDetails.setVisibility(View.VISIBLE);
                        //产品价格区间
                        goodsPrice.setText("￥ " + result.optString("goodsPrices"));
                        //商品名称
                        goodsNameStr = result.optString("name");
                        goodsName.setText(goodsNameStr);
                        //解析图片数组
                        JSONArray imgArry = result.optJSONArray("goodsImgs");
                        for (int i = 0; i < imgArry.length(); i++) {
                            String imgUrl = (String) imgArry.opt(i);
                            bean = new BannerBean(i + "", imgUrl, goodsType);
                            bannerList.add(bean);
                        }
                        //图文详情
                        graphicDetails = result.optString("graphicDetails");
                        //解析sku
                        JSONArray goodsModelArry = result.optJSONArray("goodsModel");
                        //成交的数量
                        goodsDealNumber.setText(result.optString("volume"));
                        //类型是手机
                        if (goodsType.equals("sj")) {
                            goodsParamsTv.setVisibility(View.VISIBLE);
                            goodsParamsView.setVisibility(View.VISIBLE);
                            if (goodsModelArry.length() > 0) {
                                for (int j = 0; j < goodsModelArry.length(); j++) {
                                    GoodsBean skuBean = new GoodsBean();
                                    JSONObject skuJson = goodsModelArry.optJSONObject(j);
                                    Object objectPrice = skuJson.get("price");
                                    String standardStr = skuJson.optString("standard");
                                    String colorStr = skuJson.optString("color");
                                    String editionStr = skuJson.optString("edition");
                                    //内存
                                    String storageStr = skuJson.optString("storage");
                                    skuBean.setStandard(standardStr);
                                    skuBean.setColor(colorStr);
                                    skuBean.setEdition(editionStr);
                                    skuBean.setStorage(storageStr);
                                    skuBean.setPhonePrice(Double.valueOf(objectPrice.toString()));
                                    skuBean.setStock(skuJson.optInt("stock"));
                                    skuBean.setSkuId(skuJson.optString("skuId"));
                                    //目前是限购数就是库存数
                                    skuBean.setLimitCount(skuJson.optInt("stock"));
                                    popGoodsData.add(skuBean);
                                }
                            }
                            //产品参数
                            JSONObject goodsParam = result.optJSONObject("productParams");
                            goodsParamBean.setCpuNumber(goodsParam.optString("cpuNumber"));
                            Object screenSizeObj = goodsParam.get("screenSize");
                            goodsParamBean.setScreenSize(screenSizeObj.toString());
                            goodsParamBean.setCpuRate(goodsParam.optString("cpuRate"));
                            goodsParamBean.setFrontCamera(goodsParam.optString("frontCamera"));
                            goodsParamBean.setPostCamera(goodsParam.optString("postCamera"));
                            goodsParamBean.setRam(goodsParam.optString("ram"));
                            goodsParamBean.setResolution(goodsParam.optString("resolution"));
                            goodsParamBean.setBodyMemory(result.optString("goodsStorage"));
                            //积分  价格/10
                            goodsCreditNumber.setText(result.optString("points"));
                            //解析赠品
                            JSONArray giftArray = result.optJSONArray("gifts");
                            if (giftArray.length() > 0) {
                                for (int i = 0; i < giftArray.length(); i++) {
                                    GoodsBean freeGoods = new GoodsBean();
                                    String freeGiftStr = (String) giftArray.opt(i);
                                    freeGoods.setPhoneName(freeGiftStr);
                                    freeGiftsList.add(freeGoods);
                                }
                            }
                            for (int i = 0; i < freeGiftsList.size(); i++) {
                                View view = LayoutInflater.from(this).inflate(R.layout.activity_free_goods, null);
                                TextView phoneName = (TextView) view.findViewById(R.id.free_gifts_tv);
                                phoneName.setText(freeGiftsList.get(i).getPhoneName());
                                freeGiftsLinear.addView(view);
                            }
                        } else if (goodsType.equals("accessory")) {
                            //类型是配件
                            if (goodsModelArry.length() > 0) {
                                for (int x = 0; x < goodsModelArry.length(); x++) {
                                    JSONObject partSkuObj = goodsModelArry.optJSONObject(x);
                                    GoodsBean partSkuBean = new GoodsBean();
                                    Object partSkuPrice = partSkuObj.get("price");
                                    String partColor = partSkuObj.optString("color");
                                    String partSkuId = partSkuObj.optString("accId");
                                    int partStock = partSkuObj.optInt("stock");
                                    partSkuBean.setPhonePrice(Double.valueOf(partSkuPrice.toString()));
                                    partSkuBean.setSkuId(partSkuId);
                                    partSkuBean.setColor(partColor);
                                    partSkuBean.setStock(partStock);
                                    //目前是限购数就是库存数
                                    partSkuBean.setLimitCount(partStock);
                                    popGoodsData.add(partSkuBean);
                                }
                            }
                            //产品参数入口隐藏
                            goodsParamsTv.setVisibility(View.GONE);
                            goodsParamsView.setVisibility(View.GONE);
                        }
                        //图片轮播
                        goodsViewpager.initBannerData(mPointView, bannerList, false, 1);
                        goodsViewpager.stopPlay();
                    } else {
                        Tools.toastTools(mCtx, getString(R.string.goods_no_detail_message));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                String errorMsg = json.optString(ConfigConts.ERRORMSG);
                Tools.toastTools(mCtx, errorMsg);
            }
        }

        if (what == ADD_SHOPCAR.hashCode()) {
            JSONObject json = (JSONObject) response.get();
            String status = json.optString(ConfigConts.STATUS_STRING);
            if (status.equals(ConfigConts.STATUS_SUCCESS)) {
                //加入购物车
                myShare.put(ConfigConts.IsRefresh, true);
                //弹出立马结算、继续购物的popWindow
                popupWindow.dismiss();
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showShopCarWindow();
                    }
                }, 300);
            } else {
                String errorMsg = json.optString(ConfigConts.ERRORMSG);
                Tools.toastTools(this, errorMsg);
            }
        }
    }

    @Override
    public void onFailed(int what, Response response) {
        Tools.toastTools(mCtx, getString(R.string.false_message));
    }

    /***
     * 加入购物车
     */
    public void requestAddShopCar() {
        request = NoHttp.createJsonObjectRequest(ConfigAPI.ADD_SHOPCAR, RequestMethod.POST);
        JSONObject keyJson = new JSONObject();
        JSONArray array = new JSONArray();
        String memberId = myShare.getString(ConfigConts.USER_ID, null);
        try {
            for (GoodsBean goodsBean : shopCarSet) {
                JSONObject json = new JSONObject();
                json.put("memberId", memberId);
                json.put("targetId", goodsBean.getSkuId());
                json.put("orderNum", goodsBean.getBuyNumber());
                if (goodsType.equals("sj")) {
                    json.put("type", getString(R.string.phone));
                } else if (goodsType.equals("accessory")) {
                    json.put("type", getString(R.string.part));
                }
                array.put(json);
            }
            keyJson.put("carts", array);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (array.length() > 0) {
            //这里
            request.setDefineRequestBodyForJson(keyJson);
            request.setCancelSign(ConfigAPI.ADD_SHOPCAR.hashCode());
            NoHttpCallBack.getInstance().add(mCtx, ConfigAPI.ADD_SHOPCAR.hashCode(), request, this, true, true);
        } else {
            Tools.toastTools(mCtx, getString(R.string.choose_buy_goods));
        }

    }

    /**
     * 立马结算、继续购物的popWindow
     */
    public void showShopCarWindow() {
        final WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.alpha = 0.8f;
        this.getWindow().setAttributes(lp);
        if (null == shopCarWindow) {
            View view = LayoutInflater.from(this).inflate(R.layout.activity_goods_detail_pop_shop_car, null);
            continueTv = (TextView) view.findViewById(R.id.continue_shop_btn);
            setAccountTv = (TextView) view.findViewById(R.id.set_account_btn);
            shopCarWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            shopCarWindow.setBackgroundDrawable(this.getResources().getDrawable(R.color.colorWhite));
            shopCarWindow.setFocusable(true);
            shopCarWindow.setOutsideTouchable(true);
            shopCarWindow.setAnimationStyle(R.style.my_popwindow);
        }
        //设置popview在y上的偏移量
        int y = ImageSizeUtil.setImageWidth(this, 1);
        shopCarWindow.showAsDropDown(commonLeftTv, 0, y / 2);
        continueTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shopCarWindow.dismiss();
                finish();
            }
        });
        setAccountTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shopCarWindow.dismiss();
                Intent mIntent = new Intent(ConfigConts.ACTION_FRAGMENT_PAGER);
                mIntent.putExtra("index", 2);
                sendBroadcast(mIntent);

                intent = new Intent(GoodsDetailsActivity.this, MainActivity.class);
                intent.putExtra("from_detail", true);
                startActivity(intent);
            }
        });
        shopCarWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                lp.alpha = 1.0f;
                GoodsDetailsActivity.this.getWindow().setAttributes(lp);
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != request) {
            request.cancel();
        }
    }
}
